<template>
	<view class="container">
		<view class="top_box">
			<view class="xjs-size-28">到账银行卡</view>
			<view class="lf lf-between lf-center bank_width" @click="switchcard" v-if="data.onbind&&data.onbind.bankName">
				<view class="lf" >
					<image class="bank_img" :src="data.onbind.bankLogo"></image>
					<view class="xjs-size-28">{{data.onbind.bankName}}({{data.onbind.receiverBankAccount}})</view>
				</view>
				<uni-icons type="right" size="18"></uni-icons>
			</view>
			<view class="lf lf-between lf-center bank_width" @click="addCard" v-else>
				<view class="lf xjs-size-28" >去添加银行卡</view>
				<uni-icons type="right" size="18"></uni-icons>
			</view>
		</view>
		<view class="withdrawal_box">
			<view class="xjs-size-28 xjs-mb-48">提现金额</view>
			<view class="lf lf-center xjs-size-56 withdrawal_hei">
				<text>￥</text>
				<input v-model="data.money" :disabled="data.disabledAct" class="withdrawal_input" type="digit" maxlength="9" @input="handleInput" placeholder="1.00" />
			</view>
			<view class="solid_box"></view>
			<view class="xjs-size-28">
				可提现金额{{data.allAmount}}元，<text class="all_text" @click="allWithdrawal(data.allAmount)">全部提现</text>
			</view>
		</view>
		<view class="xjs-size-26 text_box">提现申请后我们会尽快审核，提现成功后会有短信通知。</view>
		<view @tap="confirmWithdrawal" :class="['xjs-btn-primary',!parseInt(data.money)?'xjs-btn-disabled':'','btn_box']">确认提现</view>
		<uni-popup ref="popupRef" type="center" :is-mask-click="false">
			<view class="unbind_pop">
				<view class="pop_title">请输入支付密码</view>
				<view class="unbind_text linehei1">提现</view>
				<view class="bank_card linehei1">￥{{Number(data.money)}}</view>
				<input v-model="data.pwd" class="pwd_input" placeholder="请输入支付密码" maxlength="6" password type="number" />
				<view class="pop_footer_btn">
					<view class="cancel_btn" @click="btnCancel()">取消</view>
					<view @click="handleConfig" class="xjs-btn-primary confirm_btn">确认</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="popupRef1" type="bottom" :is-mask-click="false" background-color="#F9F6F6">
			<view class="change_pop">
				<view class="lf lf-center lf-between xjs-pt-36">
					<view class="xjs-ml-32 xjs-size-36">更换银行卡<text v-if="data.list&&data.list.length>0" class="xjs-size-26">（{{data.list.length}}）</text></view>
					<uni-icons @click="closeBtn" class="xjs-mr-32" type="closeempty" size="16"></uni-icons>
				</view>
				<scroll-view class="scroll-view" scroll-y="true">
					<view class="pop_list">
						<view class="list_box" :class="item.active?'pop_active':''" @click="actBtn(item)" v-for="item in data.list">
							<view class="lf">
								<image class="pop_bank_img" :src="item.bankLogo"></image>
								<view>
									<view class="xjs-size-30 xjs-weight-bold">{{item.bankName}}</view>
									<view class="xjs-size-26">*****{{item.receiverBankAccount}}</view>
								</view>
							</view>
							<uni-icons v-if="item.active" type="checkmarkempty" color="#FF6084" size="24"></uni-icons>
						</view>
						<view class="add_box" @click="addCard">
							<view class="lf lf-center">
								<image class="pop_bank_img1" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-38.png"></image>
								<view class="xjs-size-30 xjs-weight-bold">
									添加新的银行卡
								</view>
							</view>
							<uni-icons type="right" size="24"></uni-icons>
						</view>
					</view>
				</scroll-view>
				
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { useUserStoreToRefs } from '@/store/useUserStore'
	const { userInfo } = useUserStoreToRefs()
	import {useStudioStoreToRefs} from '@/store/useStudioStore'
	const {studioBalance} = useStudioStoreToRefs()
	import { nextTick, reactive, ref } from 'vue';
	import { onShow,onLoad } from '@dcloudio/uni-app'
	import {debounce} from '@/hooks/useFunction'
	import { updateUserInfo } from '@/hooks/useLogin'
	import api from '@/api'
	let data = reactive<any>({
		list: [],
		page: 1,
		limit: 20,
		onbind:{},
		pwd:'',
		loading:false,
		allAmount:'',
		money:'',
		type:'',
		studioId:'',
		userId:'',
		disabledAct:false
	})
	const handleInput = (e: any) => {
	  // 一定要加nextTick，否则特殊情况的更改不生效【如：000时，更改为0】
	  nextTick(() => {
	    let value = e.detail.value
	    // 如果当前输入为空，直接允许清空
	    if (!value) {
	      data.money = ''
	    } else if (value?.charAt(0) === '0' && value.charAt(1) && value.charAt(1) !== '.') {
	      // // 1. 当第一位为0时，只能输入小数点【第二位必须是小数点】
	      value = '0'
	    }
	    value = value.replace(/[^\d.]/g, '') // 清除"数字"和"."以外的字符
	    value = value.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
	    value = value.match(/^\d*(\.?\d{0,2})/g)[0] || '' // 保留2位小数
	    data.money = value
		
	  })
	}
	
	const backDebounce = debounce(3000)
	const handleConfig = () => {
	  backDebounce(() => {
	    submitBtn()
	  })
	}
	const getBankList = async () => {
		const res : any = await api({
			method: 'get',
			url: `/mall/bank-card/page`,
			data:{
				page: data.page,
				limit: data.limit,
			}
		})
		if (res.data.records.length <= 0) {
			data.loading = true
		}else{
			res.data.records.forEach((item)=> {
				item.active = false
				item.receiverBankAccount = item.bankAccount.substring(item.bankAccount.length-4)
			});
			data.list = res.data.records
			data.onbind = res.data.records[0]
			data.onbind.active = true
		}
	}
	//提现
	const submitBtn = async () => {
		if(!data.pwd){
			uni.showToast({
				title: '请输入支付密码',
				icon: 'none'
			})
			return
		}
		const res : any = await api({
			method: 'post',
			url: `/mall/studio/studio-balance-withdraw-record-new/withdraw`,
			data:{
				type:data.type,
				studioId:data.studioId,
				paymentPassword:data.pwd,
				amount:Number(data.money),
				cardId:data.onbind.id
			}
		})
		if(res.code=='0'){
			data.pwd = ''
			data.money = ''
			uni.showToast({
				title: '提现成功',
				icon: 'none'
			})
			data.disabledAct = false
			popupRef.value.close()
			if(data.type==2){
				getUserBalance()
			}else{
				getStudioBalance()
			}
		}else{
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
		popupRef1.value.close()
	}
	//获取工作室余额
	const getStudioBalance = async () => {
		const res : any = await api({
			method: 'get',
			url: `/mall/studio/balance/getStudioBalance/${data.studioId}`,
			
		})
		data.allAmount = res.data.balance
	}
	//获取个人余额
	const getUserBalance = async () => {
		const res : any = await api({
			method: 'get',
			url: `/mall/studio/balance/getUserBalance/${data.studioId}/${data.userId}`
		})
		data.allAmount = res.data.balance
	}
	//全部提现
	const allWithdrawal = (item: any) => {
		data.money = item
	}
	const actBtn = (item: any) => {
		data.onbind = item
		data.list.forEach((items)=> {
			items.active = false
			if(items.id == data.onbind.id){
				items.active = true
			}else{
				items.active = false
			}
		});
		popupRef1.value.close()
	}
	let popupRef = ref()
	let popupRef1 = ref()
	
	const closeBtn = () => {
		popupRef1.value.close()
	}
	const confirmWithdrawal = () => {
		if(!data.onbind){
			uni.showToast({
				title: '请先添加银行卡',
				icon: 'none'
			})
			return
		}
		if(Number(data.money)<1){
			uni.showToast({
				title: '提现金额最少1元',
				icon: 'none'
			})
			return
		}
		if(!userInfo.value.paymentPassword){
			uni.showModal({
				title: '',
				content: '还未设置支付密码',
				confirmText:'去设置',
				success: function (res) {
					if (res.confirm) {
						uni.navigateTo({
							url:'/pages/myStudio/studio/setPaymentPassword/index'
						})
					}
					if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
			return
		}
		if(Number(data.money)>Number(data.allAmount)){
			uni.showToast({
				title: '超出提现金额',
				icon: 'none'
			})
			return
		}
		popupRef.value.open()
		data.disabledAct = true
	}
	const switchcard = () => {
		popupRef1.value.open()
	}
	const addCard = () => {
		uni.navigateTo({
			url:'/pages/myStudio/studio/addBankCard/index'
		})
	}
	const btnCancel = () => {
		data.disabledAct = false
		data.pwd = ''
		popupRef.value.close()
	}
	onLoad((e) => {
		data.type = e.type
		data.studioId = e.studioId
		if(e.type==2){
			data.userId = e.userId
		}
	})
	onShow(() => {
		uni.setNavigationBarTitle({
			title: '发起提现'
		});
		updateUserInfo()
		getBankList()
		if(data.type==2){
			getUserBalance()
		}else{
			getStudioBalance()
		}
	})
</script>

<style lang="scss" scoped>
	.lf {
		display: flex;
	}

	.lf-between {
		justify-content: space-between;
	}

	.lf-center {
		align-items: center;
	}

	.container {
		padding-bottom: var(--safe-area-bottom);
	}
	.linehei1{
		line-height: 1;
	}
	.top_box {
		margin: 32rpx;
		height: 140rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #ffffff;
		border-radius: 24rpx;
		padding: 0 32rpx;
		.bank_width{
			width: 68%;
		}
	}

	.bank_img {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		margin-right: 6rpx;
	}

	.withdrawal_box {
		background-color: #ffffff;
		border-radius: 24rpx;
		margin: 32rpx;
		padding: 48rpx 32rpx;
	}
	.withdrawal_hei{
		height: 74rpx;
	}
	.withdrawal_input {
		font-size: 48rpx;
		display: block;
		height: 74rpx;
		font-weight: bold;
	}

	.solid_box {
		margin: 48rpx 0 26rpx 0;
		border-bottom: 1rpx solid #E4E6E6;
	}

	.all_text {
		color: #FF6084;
	}

	.text_box {
		margin: 26rpx 0 48rpx 32rpx;
	}

	.btn_box {
		width: 670rpx;
		margin-left: 40rpx;
	}
	.change_pop {
		width: 100%;
		background: #F9F6F6;
		border-radius: 24rpx 24rpx 0 0;
		
		box-sizing: border-box;
		.pop_bank_img{
			margin-top: 4rpx;
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			margin-right:16rpx;
		}
		.pop_bank_img1{
			margin-top: 4rpx;
			width: 48rpx;
			height: 48rpx;
			border-radius: 50%;
			margin-right:16rpx;
		}
		.pop_list{
			border-radius: 24rpx;
			margin: 0 32rpx;
			padding-bottom: 32rpx;
		}
		.list_box{
			margin-top: 32rpx;
			padding: 32rpx;
			background-color: #FFFFFF;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 24rpx
		}
		.pop_active{
			border: 1rpx solid #FF6084;
		}
		.add_box{
			margin-top: 32rpx;
			padding: 32rpx;
			background-color: #FFFFFF;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-radius: 24rpx
		}
		.scroll-view{
			height: 50vh;
			overflow: hidden;
		}
	}
	.unbind_pop {
		width: 622rpx;
		background: #FFFFFF;
		border-radius: 24rpx;
		padding: 64rpx 40rpx;
		box-sizing: border-box;
		text-align: center;

		.pop_title {
			font-weight: 500;
			font-size: 40rpx;
			color: #1B2120;

		}

		.unbind_text {
			margin-top: 48rpx;
			font-size: 30rpx;
			color: #1B2120;
		}

		.bank_card {
			margin-top: 24rpx;
			font-size: 64rpx;
			color: #1B2120;
			font-weight: bold;
		}

		.pwd_input {
			width: 100%;
			height: 128rpx;
			background: #F5F6F7;
			border-radius: 32rpx;
			border: 2rpx solid #F9F6F6;
			margin-top: 48rpx;
			font-size: 36rpx;
		}

		.pop_footer_btn {
			display: flex;
			justify-content: space-between;
			margin-top: 48rpx;

			.cancel_btn {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 263rpx;
				height: 88rpx;
				background-color: #FFFFFF;
				border-radius: 44rpx;
				border: 2rpx solid #FF6084;
				font-weight: 400;
				font-size: 28rpx;
				color: #FF6084;

			}

			.confirm_btn {
				width: 263rpx;
				height: 88rpx;
			}
		}
	}
</style>